package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.HeadRepository;
import com.chz.SupermarketMS.dao.PurchaseRepository;
import com.chz.SupermarketMS.dao.SaleRepository;
import com.chz.SupermarketMS.entities.*;
import com.chz.SupermarketMS.service.HeadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("heads")
public class HeadController {

    @Autowired
    HeadRepository headRepository;

    @Autowired
    HeadService headService;

    @Autowired
    SaleRepository saleRepository;

    @Autowired
    PurchaseRepository purchaseRepository;

    @GetMapping
    public String displayHead(Model model){
        List<Head> heads = headRepository.findAll();
        model.addAttribute("heads",heads);

        return "heads/list-heads";
    }

    @GetMapping("/new")
    public String displayHeadForm(Model model){

        Head ahead = new Head();
        List<Sale> sales = saleRepository.findAll();
        List<Purchase> purchases = purchaseRepository.findAll();
        model.addAttribute("allSales",sales);
        model.addAttribute("allPurchases",purchases);
        model.addAttribute("head",ahead);
        return "heads/new-head";
    }

    @PostMapping("/save")
    public String createHead(Model model, @RequestParam List<Long> sales, @RequestParam List<Long> purchases, @Valid Head head, Errors errors){

        if (errors.hasErrors())  return "heads/new-head";

        headRepository.save(head);

        Iterable<Sale> chosenSales = saleRepository.findAllById(sales);
        for (Sale sale : chosenSales){
            sale.setHead(head);
            saleRepository.save(sale);
        }

        Iterable<Purchase> chosenPurchases = purchaseRepository.findAllById(purchases);
        for (Purchase purchase : chosenPurchases){
            purchase.setHead(head);
            purchaseRepository.save(purchase);
        }
        return "redirect:/heads";
    }

    @GetMapping("/update")
    public String displayHeadUpdateForm(@RequestParam("id") long theId, Model model) {
        Head theHead = headService.findByHeadId(theId);
        model.addAttribute("head", theHead);
        return "heads/new-head";
    }


    @GetMapping("/delete")
    public String deleteHead(@RequestParam("id")long theId, Model model) {
        Head theHead = headService.findByHeadId(theId);
        headService.delete(theHead);
        return "redirect:/heads";
    }


}
